import { EChartOption } from 'echarts';

export default function useTooltip() {
  const getSeriesColor = (seriesItem: EChartOption.SeriesBar | EChartOption.SeriesLine) => {
    const color = seriesItem?.color;
    if (!color) return '';
    if (typeof color === 'string') {
      return color;
    } else {
      return color?.colorStops ? color?.colorStops[0].color : '';
    }
  };

  const tooltipFormatter = (series: EChartOption.Series) => {
    if (Array.isArray(series) && series.length > 0) {
      const content = series
        .map((item) => {
          const { seriesName, value, data, seriesType } = item;

          const color = getSeriesColor(item);
          const unit = data?.unit || '';
          const unitFormatter = data?.unitFormatter;
          return `<div class="tooltip-item flex items-center justify-between">
           <div class="flex items-center mr-16">
              <i 
                class="w-8 rounded-2px mr-4" 
                style="background-color: ${color};height:${seriesType === 'line' ? '2px' : '8px'} "></i>
              <div class="tooltip-item__name">${seriesName}</div>
           </div>
            <div class="tooltip-item__value" style="color:${color};">${unitFormatter ? unitFormatter(value, item) : `${value}${unit}`}</div>
          </div>`;
        })
        .join('');

      return `<div class="custom-tooltip">
        <div class="tooltip-title text-value-14__bold">${series[0].axisValueLabel}</div>
        <div class="tooltip-content text-12">${content}</div>
      </div>`;
    }
    return '';
  };

  return {
    tooltipFormatter
  };
}
